<?php

namespace App\Http\Middleware;

use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Model\User;
use App\Kuafu\User\Service\AuthService;
use Closure;
use App\Kuafu\Base\Service\BaseService;
use Tymon\JWTAuth\Http\Middleware\Authenticate;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\JWTException;

class PosJwtAuth extends Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            // 开发环境不校验，太烦了
            if (config('app.env') == 'dev' && auth('api')->user() == null) {
                $user = User::query()->first();
                if ($user) {
                    auth('api')->login($user);
                }
                return $next($request);
            }
            //检查请求是否有token
            if (!$this->auth->parser()->setRequest($request)->hasToken()) {
                throw new \Exception('Pos登录状态异常，请重新登录。', BaseCodeEnum::ERR_400009);
            }
            //检查token是否过期
            $this->auth->parseToken()->authenticate();
            //判断token是否是当前请求端
            $payload = AuthService::getPayload();
            $payload = $payload->toArray();
            if ($payload['type'] != UserCodeEnum::CODE_TEXT[UserCodeEnum::POS_TYPE]) {
                throw new \Exception(UserCodeEnum::CODE_TEXT[UserCodeEnum::ERR_USER_PAYLOAD],
                    UserCodeEnum::ERR_USER_PAYLOAD);
            }
            return $next($request);
        } catch (TokenExpiredException $e) {
            return response()->json(BaseService::returnData(BaseCodeEnum::ERR_400003));
        } catch (TokenInvalidException $e) {
            return response()->json(BaseService::returnData(BaseCodeEnum::ERR_400002));
        } catch (JWTException $ex) {
            return response()->json(BaseService::returnData(BaseCodeEnum::ERR_400009));
        } catch (\Exception $exception) {
            return response()->json(BaseService::returnData($exception->getCode(), $exception->getMessage()));
        }
    }
}
